package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.SQLListDoing;
import com.rockcent.common.common.SQLPageDoing;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.Favorite;
import com.rockcent.mall.lib.domain.enumclass.FavoriteType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by zhangjh on 2016/10/22.
 */
@Repository
public class FavoriteRepositoryImpl implements FavoriteRepositoryCustom {
    private static final Logger log = LoggerFactory.getLogger(FavoriteRepositoryImpl.class);
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
/*
    @Override
    public List<Favorite> getListFavorite(Long customerId, FavoriteType favoriteType, PageResult pageResult){
        SQLListDoing doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("SELECT %s FROM favorite f WHERE f.`customer_id`=:customerId AND f.`type` =:favoriteType AND f.`is_delete` =:isDelete  ");
            params.put("customerId",customerId);
            params.put("favorite",favoriteType.toString());
            params.put("isDelete", Whether.NO.toString());
            fields.append("f.*");
        };
        return doing.go(Favorite.class, objectMapper, jdbcTemplate, log);
    }*/

    @Override
    public PageResult<Favorite> findListFavorite(Long customerId, FavoriteType type, PageResult pageResult) {
        SQLPageDoing doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("SELECT %s FROM favorite f WHERE f.customer_id = :customerId AND f.type = :favoriteType  AND f.is_delete = :isDelete order by f.date_created desc");
            params.put("customerId",customerId);
            params.put("favoriteType",type.toString());
            params.put("isDelete", Whether.NO.toString());
            fields.append("*");
        };
        return doing.go(pageResult, Favorite.class, objectMapper, jdbcTemplate, log);
    }

    @Override
    public List<Long> getAllFavoriteProductsOrderByDateDesc(Long customerId, Long mallId) {
        SQLListDoing<Long> doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append(" select %s  from favorite f INNER JOIN product p ON f.product_id = p.id where f.customer_id =:customerId and f.mall_id=:mallId  and p.`status` ='SELLING'  order by f.id desc");
            params.put("customerId", customerId);
            params.put("mallId", mallId);
            fields.append("DISTINCT f.product_id as product_id");
        };
        return doing.go(Long.class, jdbcTemplate, log, objectMapper);
    }
}


